package cn.my.learning.service;

import cn.my.learning.domain.Comment;
import cn.my.learning.repository.CommentRepository;
import cn.my.learning.util.PageableTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Leo on 2017/4/21.
 * 评论服务层
 */
@Repository
public class CommentServiceImpl {

    @Autowired
    private CommentRepository commentRepository;

    /**
     * 获取articleCode的评论数(分页)
     * @param articleCode
     * @param current
     * @param size
     * @return
     */
    public Page<Comment> getLibraryComment(String articleCode, Integer current, Integer size){
        Pageable pageable = PageableTools.commentSort(current, size);
        return commentRepository.findByArticleCode(articleCode, pageable);
    }

    /**
     * 新建或添加评论
     * @param publishAccount
     * @param ArticleCode
     * @param commentToWho
     * @param commentPublisher
     * @param commentContent
     * @return
     */
    public boolean addLibraryComment(String publishAccount, String ArticleCode, String commentToWho, String commentPublisher, String commentContent){

        Comment comment = new Comment();

        //通过ArticleCode查询改library是否有评论，没有则新建，有则添加
        List<Comment> comments = commentRepository.findByArticleCode(ArticleCode);

        //判断文章是否有评论记录
        if (comments.size() == 0){
            //初始化评论结构
            List<Map<String, String>> commentList = new ArrayList<>();
            Map<String, String> first_comment = new HashMap<>();

            //存入ArticleCode
            comment.setArticleCode(ArticleCode);

            //评论时间
            comment.setCommentTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            //插入文章作者
            comment.setPublisherAccount(publishAccount);

            //获得评论结构的长度插入评论，没有则在第0位插入
            first_comment.put("commentToWho", commentToWho);
            first_comment.put("commentPublisher", commentPublisher);
            first_comment.put("commentContent", commentContent);

            //把评论List写入
            commentList.add(0, first_comment);
            comment.setComment(commentList);

            //写入对象
            commentRepository.insert(comment);

            return true;
        }
        //有则获得原有评论的长度
        Integer oldCommentSize = comments.get(0).getComment().size();

        //新评论
        Map<String, String> one_comment = new HashMap<>();
        one_comment.put("commentToWho", commentToWho);
        one_comment.put("commentPublisher", commentPublisher);
        one_comment.put("commentContent", commentContent);

        //添加到原有评论的下一位
        comments.get(0).getComment().add(one_comment);
        comment.setComment(comments.get(0).getComment());

        //保存
        commentRepository.save(comments);
        return true;
    }

}
